package com.sinosoft.hydra.um.services.component.dataimport.validators;

import com.sinosoft.hydra.um.services.component.dataimport.resolvers.ValidateResult;

import java.math.BigDecimal;

/**
 * Created by Administrator on 2015/1/12.
 */
public class MaxScaleValidator extends Validator {

    private int maxScale;
    private String errorMsg;

    public MaxScaleValidator(int maxScale) {
        this.maxScale = maxScale;
    }

    public MaxScaleValidator(int maxNumber, String errorMsg) {
        this.maxScale = maxNumber;
        this.errorMsg = errorMsg;
    }

    public ValidateResult validate(Object obj) {
        if (obj == null) {
            return ValidateResult.PASS();
        }
        try {
            Double val = (Double) obj;
            BigDecimal ss = BigDecimal.valueOf(val);
            if (ss.scale() > maxScale) {
                if (maxScale > 0 || ss.scale() != 1 || val != ss.intValue()) {
                    return errorMsg == null
                            ? ValidateResult.ERROR("数据小数位数最大不能超过" + maxScale + "位")
                            : ValidateResult.ERROR(errorMsg);
                }
            }
        } catch (Exception ex) {
            throw new ValidateException();
        }
        return ValidateResult.PASS();
    }
}
